﻿using Aspose.Cells;
using Aspose.Cells.Rendering;
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using TruckScale.Models;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.Helpers
{
  public class PrinterHelper
  {
    public static void PrintImg(WeighRecordModel record, string templateName, PrintMode pm)
    {
      var ws = new Workbook(".\\Data\\PrintTemplate.xlsx").Worksheets[templateName];

      if (ws == null)
      {
        SetLog("未找到打印模板", LogType.OperationLogger, LogLevel.Error);
        return;
      }

      #region 替换模板中的参数
      var goodList = GoodsModel.SelectValidGoods();
      var customerList = CustomerModel.SelectValidCustomer();
      var userList = UserModel.SelectValidUser();

      //替换规则
      FindOptions opts = new FindOptions();
      opts.LookInType = LookInType.Values;
      opts.LookAtType = LookAtType.StartWith;

      //逐个替换
      Cell cell = null;
      do
      {
        cell = ws.Cells.Find("_", cell, opts);
        if (cell != null)
        {
          string pName = Regex.Replace(cell.Value.ToString().Substring(1), "^[a-z]", m => m.Value.ToUpper());
          cell.Value = typeof(WeighRecordModel).GetProperty(pName)?.GetValue(record);

          if (pName == "Wz")
          {
            cell.Value = goodList.Find(g => g.GoodsId == Convert.ToInt32(cell.Value))?.GoodsName;
          }
          if (pName.StartsWith("Kh"))
          {
            cell.Value = customerList.Find(c => c.CustomerId == Convert.ToInt32(cell.Value))?.CustomerName;
          }
          if (pName.EndsWith("sby"))
          {
            cell.Value = userList.Find(u => u.UserId == Convert.ToInt32(cell.Value))?.UserName;
          }
        }
      } while (cell != null);
      #endregion

      try
      {
        PrintDocument pd = new PrintDocument();
        PaperSize ps = new PaperSize("自定义", Convert.ToInt32(Global._weighConfig["PaperWidth"]) * 1000 / 254, Convert.ToInt32(Global._weighConfig["PaperHeight"]) * 1000 / 254);
        pd.DefaultPageSettings.PaperSize = ps;

        pd.PrintPage += (sender, ev) =>
        {
          ev.Graphics.DrawImage(ExcelToBmp(ws), 0, 0);
          ev.HasMorePages = false;
        };

        if (Convert.ToBoolean(Global._weighConfig["PreviewPrint"]))
        {
          PrintPreviewDialog ppd = new PrintPreviewDialog();
          ppd.WindowState = FormWindowState.Maximized;
          ppd.Document = pd;
          ppd.ShowDialog();
        }
        else
        {
          string[] pList = null;
          if(pm == PrintMode.Hand)
          {
            pList = Global._weighConfig["HandWeighingPrinters"].Split(',');
          }
          if (pm == PrintMode.Once)
          {
            pList = Global._weighConfig["WeighingOncePrinters"].Split(',');
          }
          if (pm == PrintMode.Finish)
          {
            pList = Global._weighConfig["WeighingFinishPrinters"].Split(',');
          }

          foreach (var p in pList)
          {
            pd.PrinterSettings.PrinterName = p;
            for (int i = 0; i < Convert.ToInt32(Global._weighConfig["PrintCopies"]); i++)
            {
              pd.Print();
            }
          }
        }
      }
      catch { }
    }

    //使用aspose插件将excel转换为图片
    private static Bitmap ExcelToBmp(Worksheet ws)
    {
      ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
      imgOptions.OnePagePerSheet = true;
      SheetRender sr = new SheetRender(ws, imgOptions);
      Bitmap bitmap = sr.ToImage(0);

      return bitmap;
    }

    public enum PrintMode
    {
      Once,
      Finish,
      Hand
    }
  }
}
